﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FYP14
{
    public partial class ViewShedule : System.Web.UI.Page
    {
        private DataTable table;

        protected void Page_Load(object sender, EventArgs e)
        {
            initData();
            if (!IsPostBack)
            {
                DayPilotMonth1.StartDate = DateTime.Today.AddDays(-7);
                //DayPilotMonth1.DataSource = getData(DayPilotMonth1.VisibleStart, DayPilotMonth1.VisibleEnd, (string)DayPilotMonth1.ClientState["filter"]);
                DayPilotMonth1.DataSource = getData(Convert.ToDateTime("2014-05-12"), Convert.ToDateTime("2014-05-18"), (string)DayPilotMonth1.ClientState["filter"]);
                DataBind();
            }
        }

        /// <summary>
        /// This method should normally load the data from the database.
        /// We will load our copy from a Session, just simulating a database.
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        private DataTable getData(DateTime start, DateTime end, string filter)
        {
            String select;
            if (String.IsNullOrEmpty(filter))
            {
                select = String.Format("NOT (([end] <= '{0:s}') OR ([start] >= '{1:s}'))", start, end, filter);
            }
            else
            {
                select = String.Format("NOT (([end] <= '{0:s}') OR ([start] >= '{1:s}')) and [name] like '%{2}%'", start, end, filter);
                //            throw new Exception(select);
            }


            DataRow[] rows = table.Select(select);

            DataTable filtered = table.Clone();

            foreach (DataRow r in rows)
            {
                filtered.ImportRow(r);
            }

            return filtered;
        }

        /// <summary>
        /// Make sure a copy of the data is in the Session so users can try changes on their own copy.
        /// </summary>
        private void initData()
        {
            if (Session["MonthView"] == null)
            {
                Session["MonthView"] = DataGeneratorMonth.GetData();
            }

            table = (DataTable)Session["MonthView"];
        }
    }
}